# -*- coding: utf-8 -*-

import json
import logging
from datetime import datetime
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import ValidationError, AccessError
import io
import jwt

_logger = logging.getLogger(__name__)


class WorkshopController(http.Controller):
    """车间管理控制器"""

    def _verify_jwt_token(self):
        """验证JWT token"""
        try:
            # 从请求头获取token
            auth_header = request.httprequest.headers.get('Authorization')
            if not auth_header or not auth_header.startswith('Bearer '):
                return None
            
            token = auth_header.split(' ')[1]
            
            # 解码token
            secret_key = request.env['device.api.config'].sudo().get_jwt_secret()
            payload = jwt.decode(token, secret_key, algorithms=['HS256'])
            
            # 获取用户
            user = request.env['device.user'].sudo().browse(payload['user_id'])
            if user.exists() and user.status == '0' and user.del_flag == '0':
                return user
            
            return None
        except jwt.ExpiredSignatureError:
            return None
        except jwt.InvalidTokenError:
            return None
        except Exception as e:
            _logger.error(f"验证token异常: {str(e)}")
            return None

    def _get_current_device_user(self):
        """获取当前device用户"""
        return self._verify_jwt_token()

    def _check_permission(self, operation='read'):
        """检查权限"""
        device_user = self._get_current_device_user()
        if not device_user:
            return False
        
        # 超级管理员拥有所有权限
        if device_user.is_admin:
            return True
        
        return True

    @http.route('/api/workshop/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def list_workshop(self, **kwargs):
        """获取车间列表"""
        try:
            if not self._check_permission('read'):
                return {
                    'code': 403,
                    'msg': '没有权限访问车间信息',
                    'data': None
                }
            
            page = kwargs.get('pageNum', 1)
            size = kwargs.get('pageSize', 10)
            name = kwargs.get('name', '')
            code = kwargs.get('code', '')
            status = kwargs.get('status', '')
            department_id = kwargs.get('departmentId', '')
            
            domain = []
            if name:
                domain.append(('name', 'ilike', name))
            if code:
                domain.append(('code', 'ilike', code))
            if status is not None and status != '':
                domain.append(('status', '=', bool(int(status))))
            if department_id:
                domain.append(('department_id', '=', int(department_id)))
            
            # 计算总数
            total = request.env['device.workshop'].sudo().search_count(domain)
            
            # 获取数据
            offset = (page - 1) * size
            workshops = request.env['device.workshop'].sudo().search(domain, offset=offset, limit=size)
            
            # 构建返回数据
            rows = []
            for workshop in workshops:
                rows.append({
                    'workshopId': workshop.id,
                    'name': workshop.name,
                    'code': workshop.code,
                    'description': workshop.description or '',
                    'departmentId': workshop.department_id.id if workshop.department_id else None,
                    'departmentName': workshop.department_id.name if workshop.department_id else '',
                    'managerId': workshop.manager_id.id if workshop.manager_id else None,
                    'managerName': workshop.manager_id.nick_name if workshop.manager_id else '',
                    'phone': workshop.phone or '',
                    'location': workshop.location or '',
                    'area': workshop.area,
                    'sequence': workshop.sequence,
                    'status': workshop.status,
                    'deviceCount': workshop.device_count,
                    'createTime': workshop.create_time.strftime('%Y-%m-%d %H:%M:%S') if workshop.create_time else '',
                    'remark': workshop.remark or ''
                })
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'total': total,
                    'rows': rows
                }
            }
            
        except Exception as e:
            _logger.error(f"获取车间列表异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'查询失败: {str(e)}',
                'data': None
            }

    @http.route('/api/workshop/info/<int:workshop_id>', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def get_workshop(self, workshop_id, **kwargs):
        """获取车间详情"""
        try:
            if not self._check_permission('read'):
                return {
                    'code': 403,
                    'msg': '没有权限访问车间信息',
                    'data': None
                }
            
            workshop = request.env['device.workshop'].sudo().browse(workshop_id)
            if not workshop.exists():
                return {
                    'code': 404,
                    'msg': '车间不存在',
                    'data': None
                }
            
            data = {
                'workshopId': workshop.id,
                'name': workshop.name,
                'code': workshop.code,
                'description': workshop.description or '',
                'departmentId': workshop.department_id.id if workshop.department_id else None,
                'departmentName': workshop.department_id.name if workshop.department_id else '',
                'managerId': workshop.manager_id.id if workshop.manager_id else None,
                'managerName': workshop.manager_id.nick_name if workshop.manager_id else '',
                'phone': workshop.phone or '',
                'location': workshop.location or '',
                'area': workshop.area,
                'sequence': workshop.sequence,
                'status': workshop.status,
                'deviceCount': workshop.device_count,
                'createTime': workshop.create_time.strftime('%Y-%m-%d %H:%M:%S') if workshop.create_time else '',
                'updateTime': workshop.update_time.strftime('%Y-%m-%d %H:%M:%S') if workshop.update_time else '',
                'createBy': workshop.create_by,
                'updateBy': workshop.update_by,
                'remark': workshop.remark or ''
            }
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': data
            }
            
        except Exception as e:
            _logger.error(f"获取车间详情异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'查询失败: {str(e)}',
                'data': None
            }

    @http.route('/api/workshop/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def add_workshop(self, **kwargs):
        """新增车间"""
        try:
            if not self._check_permission('create'):
                return {
                    'code': 403,
                    'msg': '没有权限创建车间',
                    'data': None
                }
            
            name = kwargs.get('name')
            code = kwargs.get('code')
            description = kwargs.get('description', '')
            department_id = kwargs.get('departmentId')
            manager_id = kwargs.get('managerId')
            phone = kwargs.get('phone', '')
            location = kwargs.get('location', '')
            area = kwargs.get('area', 0.0)
            sequence = kwargs.get('sequence', 10)
            status = kwargs.get('status', True)
            remark = kwargs.get('remark', '')
            
            if not name or not code or not department_id:
                return {
                    'code': 400,
                    'msg': '车间名称、车间编码、所属部门为必填项',
                    'data': None
                }
            
            vals = {
                'name': name,
                'code': code,
                'description': description,
                'department_id': int(department_id),
                'phone': phone,
                'location': location,
                'area': float(area),
                'sequence': int(sequence),
                'status': bool(status),
                'remark': remark
            }
            
            if manager_id:
                vals['manager_id'] = int(manager_id)
            
            workshop = request.env['device.workshop'].sudo().create(vals)
            
            return {
                'code': 200,
                'msg': '车间创建成功',
                'data': {'workshopId': workshop.id}
            }
            
        except ValidationError as e:
            return {
                'code': 400,
                'msg': str(e),
                'data': None
            }
        except Exception as e:
            _logger.error(f"创建车间异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'创建失败: {str(e)}',
                'data': None
            }

    @http.route('/api/workshop/edit', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def edit_workshop(self, **kwargs):
        """修改车间"""
        try:
            if not self._check_permission('write'):
                return {
                    'code': 403,
                    'msg': '没有权限修改车间',
                    'data': None
                }
            
            workshop_id = kwargs.get('workshopId')
            if not workshop_id:
                return {
                    'code': 400,
                    'msg': '车间ID不能为空',
                    'data': None
                }
            
            workshop = request.env['device.workshop'].sudo().browse(int(workshop_id))
            if not workshop.exists():
                return {
                    'code': 404,
                    'msg': '车间不存在',
                    'data': None
                }
            
            vals = {}
            if 'name' in kwargs:
                vals['name'] = kwargs['name']
            if 'code' in kwargs:
                vals['code'] = kwargs['code']
            if 'description' in kwargs:
                vals['description'] = kwargs['description']
            if 'departmentId' in kwargs:
                vals['department_id'] = int(kwargs['departmentId'])
            if 'managerId' in kwargs:
                vals['manager_id'] = int(kwargs['managerId']) if kwargs['managerId'] else False
            if 'phone' in kwargs:
                vals['phone'] = kwargs['phone']
            if 'location' in kwargs:
                vals['location'] = kwargs['location']
            if 'area' in kwargs:
                vals['area'] = float(kwargs['area'])
            if 'sequence' in kwargs:
                vals['sequence'] = int(kwargs['sequence'])
            if 'status' in kwargs:
                vals['status'] = bool(kwargs['status'])
            if 'remark' in kwargs:
                vals['remark'] = kwargs['remark']
            
            workshop.write(vals)
            
            return {
                'code': 200,
                'msg': '车间修改成功',
                'data': None
            }
            
        except ValidationError as e:
            return {
                'code': 400,
                'msg': str(e),
                'data': None
            }
        except Exception as e:
            _logger.error(f"修改车间异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'修改失败: {str(e)}',
                'data': None
            }

    @http.route('/api/workshop/delete', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def delete_workshop(self, **kwargs):
        """删除车间"""
        try:
            if not self._check_permission('unlink'):
                return {
                    'code': 403,
                    'msg': '没有权限删除车间',
                    'data': None
                }
            
            workshop_ids = kwargs.get('workshopIds', [])
            if not workshop_ids:
                return {
                    'code': 400,
                    'msg': '请选择要删除的车间',
                    'data': None
                }
            
            workshops = request.env['device.workshop'].sudo().browse(workshop_ids)
            workshops.unlink()
            
            return {
                'code': 200,
                'msg': '车间删除成功',
                'data': None
            }
            
        except Exception as e:
            _logger.error(f"删除车间异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'删除失败: {str(e)}',
                'data': None
            }

    @http.route('/api/workshop/export', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    def export_workshop(self, **kwargs):
        """导出车间信息"""
        try:
            if not self._check_permission('read'):
                return request.make_response(
                    json.dumps({'code': 403, 'msg': '没有权限导出车间信息'}),
                    headers=[('Content-Type', 'application/json')]
                )
            
            # 获取查询条件
            name = kwargs.get('name', '')
            code = kwargs.get('code', '')
            status = kwargs.get('status', '')
            department_id = kwargs.get('departmentId', '')
            
            domain = []
            if name:
                domain.append(('name', 'ilike', name))
            if code:
                domain.append(('code', 'ilike', code))
            if status is not None and status != '':
                domain.append(('status', '=', bool(int(status))))
            if department_id:
                domain.append(('department_id', '=', int(department_id)))
            
            workshops = request.env['device.workshop'].sudo().search(domain)
            
            # 构建Excel数据
            import xlsxwriter
            output = io.BytesIO()
            workbook = xlsxwriter.Workbook(output)
            worksheet = workbook.add_worksheet('车间信息')
            
            # 设置标题
            headers = [
                '车间编码', '车间名称', '车间描述', '所属部门', '车间负责人',
                '联系电话', '车间位置', '车间面积(㎡)', '排序', '状态',
                '设备数量', '创建时间', '备注'
            ]
            
            # 写入标题
            for col, header in enumerate(headers):
                worksheet.write(0, col, header)
            
            # 写入数据
            for row, workshop in enumerate(workshops, 1):
                data = [
                    workshop.code,
                    workshop.name,
                    workshop.description or '',
                    workshop.department_id.name if workshop.department_id else '',
                    workshop.manager_id.nick_name if workshop.manager_id else '',
                    workshop.phone or '',
                    workshop.location or '',
                    workshop.area,
                    workshop.sequence,
                    '启用' if workshop.status else '停用',
                    workshop.device_count,
                    workshop.create_time.strftime('%Y-%m-%d %H:%M:%S') if workshop.create_time else '',
                    workshop.remark or ''
                ]
                
                for col, value in enumerate(data):
                    worksheet.write(row, col, value)
            
            workbook.close()
            output.seek(0)
            
            # 生成文件名
            filename = f"车间信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
            
            response = request.make_response(
                output.getvalue(),
                headers=[
                    ('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                    ('Content-Disposition', f'attachment; filename="{filename}"')
                ]
            )
            output.close()
            return response
            
        except Exception as e:
            _logger.error(f"导出车间信息异常: {str(e)}")
            return request.make_response(
                json.dumps({'code': 500, 'msg': f'导出失败: {str(e)}'}),
                headers=[('Content-Type', 'application/json')]
            )
